function identity (value) {
    return value
}

function handleAction (actionType, reducer = identity) {
    return (state, action) => {
        const { type } = action
        if (actionType === type) {
            return reducer(state, action)
        }
        return state
    }
}

// 所有的reducers都执行一遍，得到最后的返回值
function reduceReducers (...reducers) {
    return (state, action) => 
        reducers.reduce((p, r) => r(p, action), state)
}

function handleActions (handlers, defaultState) {
    const reducers = Object.keys(handlers).map(type => 
        handleAction(type, handlers[type])
    )
    const reducer = reduceReducers(...reducers)
    return (state = defaultState, action) => reducer(state, action)
}

export default handleActions

// {
//     a (state, payload) {
//         return state
//     },
//     b (state, payload) {
//         return state
//     }
// }

// const funs = [
//     function (state, action) {
//         if (action.type === 'a') return 'a' 
//         return state
//     },
//     function (state, action) {
//         if (action.type === 'b') return 'b'
//         return state
//     }
// ]

// function reduceReducers (...reducers) {
//     return function (previous, current) {
//         var ret = reducers.reduce((p, r) => r(p, current), previous)
//         return ret
//     }
// }

// // previous-state, current-action 所有的reducers都执行一遍，得到最后的返回值
// function reducer (previous, current) {
//     var ret = funs.reduce((p, r) => r(p, current), previous)
//     return ret
// }